package com.xyp.iodemo.nettyrpcclient.netty;

import com.xyp.iodemo.nettyrpcclient.interfaces.INettyCallBack;
import com.xyp.iodemo.nettyrpccommon.model.RPCNetty;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.logging.Logger;

/**
 * @author xuyuanpeng
 * @version 1.0
 * @date 2019-04-09 21:06
 */
public class RPCFactory {
    private static java.util.logging.Logger logger = Logger.getLogger("EchoClientHandler");

    public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr, final INettyCallBack nettyCallBack) {
        // 1.将本地的接口调用转换成JDK的动态代理，在动态代理中实现接口的远程调用
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(),
                new Class<?>[]{serviceInterface},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        logger.info("invoke");
                        EchoClient echoClient=new EchoClient(addr);
                        RPCNetty rpcNetty=new RPCNetty();
                        rpcNetty.setClzName(serviceInterface.getName());
                        rpcNetty.setMethodName(method.getName());
                        rpcNetty.setParamTypes(method.getParameterTypes());
                        rpcNetty.setArguments(args);
                        echoClient.setRpcNetty(rpcNetty);
                        echoClient.setNettyCallBack(nettyCallBack);
                        echoClient.start();
                        return null;
                    }
                });
    }
}
